<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\User;
use app\BaseController;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;
use think\response\Json;

class Index extends BaseController
{
    protected $model;
    protected function initialize()
    {
        parent::initialize();
        $this->model = new User();
    }

    public function login()
    {
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');

        if (!$username || !$password) {
            return $this->error('用户名或密码不能为空');
        }
        $data = $this->model->where('username', $username)->find();
        if ($data->isEmpty()) {
            return $this->error('用户名或密码错误');
        }
        if ($data['password'] !== md5($data->salt . $password)) {
            return $this->error('用户名或密码错误');
        }
        $userInfo = [
            'uid' => $data['id'],
            'username' => $data['username'],
            'avatar' => $data['avatar'],
            'nickname' => $data['nickname']
        ];
        $token = JWTAuth::builder($userInfo);
        return $this->success('登录成功', ['token' => $token, 'userInfo' => $userInfo]);
    }

    public function getMenu() : Json
    {
        $contents = file_get_contents(root_path() . 'public/static/menu.json');
        $data = json_decode($contents, true);
        return $this->success('获取成功', $data);
    }


    public function index()
    {
        $contents = file_get_contents(root_path() . 'public/static/menu.json');
        $json = json_decode($contents, true);
        $menu = $json['menu'];
        halt($menu);
    }

}
